<template>
  <div style="padding: 20px;">
    <si-table
      ref="dragTable"
      :table-columns="tableColumns"
      :table-data="tableData"
      :table-operation="tableOperation"
      :is-selection="true"
      :row-class-name="rowClassName"
      :table-key="tableKey"
      @handleSelectionChange="handleSelectionChange"
    >
      <template v-slot:status="props">
        <el-button type="danger" size="small">{{
          props.scope.row.status === 0 ? '启用' : '禁用'
        }}</el-button>
      </template>
      <!-- 自定义操作部分 -->
      <!-- <template v-slot:[tableOperation.param]="props">
        <span v-for="(item, index) in tableOperation.btnList" :key="index" @click="handleClick(props.scope.row, item.type)">{{item.label}}</span>
      </template> -->
    </si-table>
    <el-divider content-position="left">拖拽结果</el-divider>
    <div class="show-d"><el-tag>The default order :</el-tag> {{ idList }}</div>
    <div class="show-d">
      <el-tag>The after dragging order :</el-tag> {{ newList }}
    </div>
  </div>
</template>

<script>
import Sortable from 'sortablejs'
// import cloneDeep from 'lodash/cloneDeep'
import { genarateTree } from '@/utils/deepProcess'
export default {
  name: 'DemoTable',
  components: {},
  data() {
    return {
      tableColumns: [
        {
          param: 'date',
          lable: '日期',
          sortable: true,
          width: '180px'
        },
        {
          param: 'name',
          lable: '姓名'
        },
        {
          param: 'status',
          lable: '状态',
          slotName: 'status'
        },
        {
          param: 'address',
          lable: '地址',
          width: '400px'
        },
        {
          param: 'gender',
          lable: '性别',
          render: row => {
            return row.gender === 0 ? '女' : '男'
          }
        }
      ],
      tableData: [
        {
          id: '1',
          date: '2016-05-02',
          name: '王小虎',
          address: '上海市普陀区金沙江路 1518 弄',
          gender: 0,
          status: 0,
          parentid: '',
          children: [
            {
              id: '11',
              date: '2016-05-21',
              name: '王小虎',
              address: '上海市普陀区金沙江路 1518 弄',
              gender: 0,
              status: 0,
              parentid: '1',
              children: [
                {
                  id: '111',
                  date: '2016-05-2333',
                  name: '王小虎',
                  address: '上海市普陀区金沙江路 1518 弄',
                  gender: 0,
                  status: 0,
                  parentid: '11',
                  children: [
                    {
                      id: '1111',
                      date: '2016-05-22',
                      name: '王小虎',
                      address: '上海市普陀区金沙江路 1518 弄',
                      gender: 0,
                      status: 0,
                      parentid: '111'
                    }
                  ]
                }
              ]
            },
            {
              id: '12',
              date: '2016-05-224444',
              name: '王小虎',
              address: '上海市普陀区金沙江路 1518 弄',
              gender: 0,
              status: 0,
              parentid: '1'
            }
          ]
        },
        {
          id: '2',
          date: '2016-05-03',
          name: '王小虎',
          address: '上海市普陀区金沙江路 1517 弄',
          gender: 1,
          status: 1,
          parentid: ''
        },
        {
          id: '3',
          date: '2016-05-04',
          name: '王小虎',
          address: '上海市普陀区金沙江路 1519 弄',
          gender: 0,
          status: 1,
          parentid: '',
          children: [
            {
              id: '31',
              date: '2016-05-41',
              name: '王小虎',
              address: '上海市普陀区金沙江路 1518 弄',
              gender: 0,
              status: 0,
              parentid: '3'
            },
            {
              id: '32',
              date: '2016-05-42',
              name: '王小虎',
              address: '上海市普陀区金沙江路 1518 弄',
              gender: 0,
              status: 0,
              parentid: '3'
            }
          ]
        },
        {
          id: '4',
          date: '2016-05-05',
          name: '王小虎',
          address: '上海市普陀区金沙江路 1516 弄',
          gender: 0,
          status: 0,
          parentid: ''
        }
      ],
      tableOperation: {
        label: '操作',
        param: 'operate',
        childDefault: false,
        fixed: 'right',
        btnList: [
          {
            label: '编辑',
            click: this.handleEdit
          },
          {
            label: '删除',
            click: this.handleDel
          }
        ]
      },
      idList: [], // 扁平化所有的原数据的id
      newList: [], // 扁平化所有的原数据
      sortable: {},
      tableKey: '',
      idLen: {}, // 记录每一个id所包含的子集个数
      currentid: ''
    }
  },
  watch: {
    tableData: {
      handler(val, oldVal) {
        // console.log(val)
      },
      deep: true
    }
  },
  mounted() {
    this.$nextTick(() => {
      // this.idList = this.tableData.map(v => v.id)
      // this.newList = this.oldList.slice()
      this.flatten(this.tableData)
      // console.log('this.newList')
    })
  },
  updated() {
    this.setSort()
  },
  methods: {
    genarateTree,
    handleEdit(row) {
      console.log(row)
      alert('编辑')
    },
    handleDel(row) {
      console.log(row)
      // 更新 idLen 中对应id所包含的子集个数 -1
      // this.idLen[row.id] = this.idLen[row.id] - 1
      alert('删除')
    },
    handleSelectionChange(val) {
      console.log(val)
    },
    rowClassName({ row, rowIndex }) {
      // console.log(row, 'rowClassName')
      return `parentid_${row.parentid ? row.parentid : 0} id_${
        row.id ? row.id : 0
      }`
    },
    // 数据扁平化
    flatten(array) {
      const vm = this
      array.map(v => {
        const obj = {}
        for (const key in v) {
          if (key !== 'children') {
            obj[key] = v[key]
          }
        }

        this.idList.push(v['id'])
        this.idLen[v['id']] =
          v['children'] && v['children'].length
            ? vm.getChildrenLen(v.children, 0)
            : 0
        this.newList.push(obj)
        if (v['children'] && v['children'].length) {
          vm.flatten(v['children'])
        }
      })
    },
    getChildrenLen(parent, len) {
      parent.forEach(o => {
        len += 1
        if (o.children && o.children.length) {
          len = this.getChildrenLen(o.children, len)
        }
      })
      return len
    },
    setSort() {
      const el = this.$refs.dragTable.$el.querySelectorAll(
        '.el-table__body-wrapper > table > tbody'
      )[0]
      this.sortable = null
      this.sortable = Sortable.create(el, {
        // draggable: '.el-table__row--level-1',
        ghostClass: 'sortable-ghost', // Class name for the drop placeholder,
        setData: function(dataTransfer) {
          // to avoid Firefox bug
          // Detail see : https://github.com/RubaXa/Sortable/issues/1012
          dataTransfer.setData('Text', '')
        },
        onStart: evt => {
          // console.log(evt.item.classList[1])
          this.currentid = evt.item.classList[2].split('_')[1]
          this.sortable.options.draggable = `.${evt.item.classList[1]}`
        },
        onEnd: evt => {
          // const targetRow = this.list.splice(evt.oldIndex, 1)[0]
          // this.list.splice(evt.newIndex, 0, targetRow)

          // // for show the changes, you can delete in you code
          const moveItemsId = this.idList.splice(
            evt.oldIndex,
            parseInt(this.idLen[this.currentid]) + 1
          )
          const moveItems = this.newList.splice(
            evt.oldIndex,
            parseInt(this.idLen[this.currentid]) + 1
          )
          // console.log(idIndex, 'idIndex')
          this.idList.splice(evt.newIndex, 0, ...moveItemsId)
          this.newList.splice(evt.newIndex, 0, ...moveItems)
          // this.genarateTree(this.newList)
          // console.log(this.genarateTree(this.newList))
          // console.log(this.newList)
          var newval = this.genarateTree(this.newList)
          console.log(this.newList)
          console.log(newval)
          this.tableData = newval
          // 更新table
          this.tableKey = new Date().getTime().toString()
        }
      })
    }
  }
}
</script>
